package com.zjun.demo.experimentaldemo.gallery_monitoring

import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.zjun.demo.experimentaldemo.R
import com.zjun.demo.experimentaldemo.base.BaseActivity
import com.zjun.demo.experimentaldemo.databinding.ActivityEventsBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 监听图片增加或者删除
 */
class EventsActivity : BaseActivity<ActivityEventsBinding>() {

    val json = "{\"code\":\"success\",\"msg\":\"Success\",\"data\":{\"events\":[{\"id\":\"137508\",\"deviceUid\":\"doorbe0001000057\",\"event\":4,\"cloud\":\"doorbe0001000057-100464018,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://us-east-1-monitor-picture.s3.us-east-1.amazonaws.com/30d/doorbe0001000057/1745927545563-4.jpg\",\"startTime\":1745927545563,\"endTime\":1745927550563},{\"id\":\"137502\",\"deviceUid\":\"S14G250001000028\",\"event\":506,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926437512-4.jpg\",\"startTime\":1745926437512,\"endTime\":1745926442512},{\"id\":\"137500\",\"deviceUid\":\"S14G250001000028\",\"event\":501,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926069240-4.jpg\",\"startTime\":1745926069240,\"endTime\":1745926074240},{\"id\":\"137499\",\"deviceUid\":\"S14G250001000028\",\"event\":2,\"cloud\":\"\",\"card\":\"\",\"icon\":\"\",\"startTime\":1745895629000,\"endTime\":1745895629000},{\"id\":\"137500\",\"deviceUid\":\"S14G250001000028\",\"event\":501,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926069240-4.jpg\",\"startTime\":1745892029000,\"endTime\":1745892029000},{\"id\":\"137500\",\"deviceUid\":\"S14G250001000028\",\"event\":501,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926069240-4.jpg\",\"startTime\":1745891400000,\"endTime\":1745891400000},{\"id\":\"137500\",\"deviceUid\":\"S14G250001000028\",\"event\":501,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926069240-4.jpg\",\"startTime\":1745891340000,\"endTime\":1745891340000},{\"id\":\"137500\",\"deviceUid\":\"S14G250001000028\",\"event\":501,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926069240-4.jpg\",\"startTime\":1745891280000,\"endTime\":1745891280000},{\"id\":\"137500\",\"deviceUid\":\"S14G250001000028\",\"event\":501,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926069240-4.jpg\",\"startTime\":1745891220000,\"endTime\":1745891220000},{\"id\":\"137500\",\"deviceUid\":\"S14G250001000028\",\"event\":501,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926069240-4.jpg\",\"startTime\":1745891160000,\"endTime\":1745891160000},{\"id\":\"137500\",\"deviceUid\":\"S14G250001000028\",\"event\":501,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926069240-4.jpg\",\"startTime\":1745891040000,\"endTime\":1745891040000},{\"id\":\"137500\",\"deviceUid\":\"S14G250001000028\",\"event\":501,\"cloud\":\"S14G250001000028-96473264,aws-cn-north-1\",\"card\":\"\",\"icon\":\"https://usecampic.efercro.com/60d/S14G250001000028/1745926069240-4.jpg\",\"startTime\":1745890980000,\"endTime\":1745890980000}],\"deviceUid\":null,\"hasNext\":false}}"

    private lateinit var adapter: EventAdapter

    private var currentPage = 1

    private var isLoading = false

    override fun initialize() {
        setupRecyclerView()
        setupRefreshLayout()
        loadData()
    }

    override fun getLayoutId(): Int = R.layout.activity_events

    private fun setupRecyclerView() {
        // 初始分组处理
        adapter = EventAdapter(
            onGroupClick = { group ->
// 1. 直接在现有分组列表上修改isExpanded状态

            },
            onItemClick = { event ->
                // 处理事件点击
            }
        )

        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(this@EventsActivity)
            adapter = this@EventsActivity.adapter
            addItemDecoration(StickyHeaderDecoration(this@EventsActivity.adapter))
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (!recyclerView.canScrollVertically(1) && !isLoading) {
                        loadMoreData()
                    }
                }
            })
        }
    }

    private fun setupRefreshLayout() {
        mBinding.swipeRefresh.setOnRefreshListener {
            currentPage = 1
            loadData()
        }
    }

    private fun loadData() {
        isLoading = true
        mBinding.swipeRefresh.isRefreshing = true

        // 模拟网络请求
        lifecycleScope.launch {
            delay(1000) // 模拟网络延迟
            val response = parseJsonToEvents(json)
            val groupedEvents = processEvents(response)

            withContext(Dispatchers.Main) {
                adapter.submitList(groupedEvents)
                mBinding.swipeRefresh.isRefreshing = false
                isLoading = false
            }
        }
    }

    private fun loadMoreData() {
        if (isLoading) return
        isLoading = true

        lifecycleScope.launch {
            delay(1000)
            val newEvents = parseJsonToEvents(json)
            val currentGroups = adapter.currentList.toMutableList()

            // 合并新数据到现有分组
            processEvents(newEvents).forEach { newGroup ->
                val existingGroup = currentGroups.find { it.hour == newGroup.hour }
                if (existingGroup != null) {
                    existingGroup.events.addAll(newGroup.events)
                } else {
                    currentGroups.add(newGroup)
                }
            }

            withContext(Dispatchers.Main) {
                adapter.submitList(currentGroups.sortedByDescending { it.timeInMillis })
                isLoading = false
                currentPage++
            }
        }
    }

    private fun parseJsonToEvents(json: String): List<Event> {
        val gson = Gson()
        val response = gson.fromJson(json, JsonObject::class.java)
        val sdf1 = response.getAsJsonObject("data").getAsJsonArray("events")
        val sdf = response.getAsJsonArray("events")
        return gson.fromJson(sdf1, object : TypeToken<List<Event>>() {}.type)
    }

    fun processEvents(events: List<Event>): List<EventGroup> {
        // 按小时分组
        val grouped = events.groupBy { event ->
            SimpleDateFormat("HH:00", Locale.getDefault()).format(Date(event.startTime))
        }.map { (hour, eventsInHour) ->
            EventGroup(
                hour = hour,
                timeInMillis = eventsInHour.minByOrNull { it.startTime }?.startTime ?: 0,
                events = eventsInHour.toMutableList()
            )
        }

        // 按时间倒序排序
        return grouped.sortedByDescending { it.timeInMillis }
    }

}